<?php

namespace App\Admin\Controllers;

use App\Models\AdminUser;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Encore\Admin\Controllers\AuthController as BaseAuthController;

class AuthController extends BaseAuthController
{


    public function postLogin(Request $request)
    {


        $this->validator($request->all(), $request->getClientIp())->validate();

        $credentials = $request->only([$this->username(), 'password']);
        $remember = $request->get('remember', false);

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return back()->withInput()->withErrors([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    protected function validator(array $data, $ip): \Illuminate\Contracts\Validation\Validator
    {


        if ($data['username']) {

            $user = AdminUser::where('username', $data['username'])->first();

            if ($user->isAdministrator()) {
                return Validator::make($data, [
                    $this->username()   => 'required',
                    'password'          => 'required',
                ], [
                    'username.required' => '请输入用户名2',
                    'password.required' => '请输入密码2'
                ]);
            }
            $data['ip'] = $ip;
            return Validator::make($data, [
                $this->username()   => 'required',
                'password'          => 'required',
//                'ip'                => Rule::in(explode(',', $user->ips))
            ], [
//                'ip.in' => '当前IP不允许登入,请联系管理员',
                'username.required' => '请输入用户名3',
                'password.required' => '请输入密码3'
            ]);
        }
        return Validator::make($data, [
            $this->username()   => 'required',
            'password'          => 'required',
        ], [
            'username.required' => '请输入用户名',
            'password.required' => '请输入密码'
        ]);

    }
}
